package com.ailanyin.admin.controller;

import com.ailanyin.admin.service.SysPostService;
import com.ailanyin.admin.service.SysRoleService;
import com.ailanyin.admin.service.SysUserService;
import com.ailanyin.common.result.AjaxResult;
import com.ailanyin.common.result.CommonPage;
import com.ailanyin.common.utils.EmptyUtil;
import com.ailanyin.common.utils.ExcelUtil;
import com.ailanyin.model.SysRole;
import com.ailanyin.model.SysUser;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/15 0015 下午 15:11
 */
@RestController
@RequestMapping("/system/user")
@Api(tags = "后台用户管理")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysPostService sysPostService;


    @PostMapping
    @ApiOperation(value = "新增用户")
    @PreAuthorize("hasAuthority('system:user:add')")
    public AjaxResult insertUser(@Validated @RequestBody SysUser user) {
        sysUserService.insertUser(user);
        return AjaxResult.success();
    }

    @PutMapping
    @ApiOperation(value = "修改用户")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public AjaxResult updateUser(@Validated @RequestBody SysUser user) {
        sysUserService.updateUser(user);
        return AjaxResult.success();
    }

    @DeleteMapping("/{userIds}")
    @ApiOperation(value = "批量删除用户")
    @PreAuthorize("hasAuthority('system:user:remove')")
    public AjaxResult removeUser(@PathVariable Long[] userIds) {
        sysUserService.deleteUserByIds(userIds);
        return AjaxResult.success();
    }

    @PutMapping("/resetPwd")
    @ApiOperation(value = "重置密码")
    @PreAuthorize("hasAuthority('system:user:resetPwd')")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        sysUserService.resetPwd(user);
        return AjaxResult.success();
    }

    @PutMapping("/changeStatus")
    @ApiOperation(value = "修改状态")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        sysUserService.updateUserStatus(user);
        return AjaxResult.success();
    }

    @GetMapping("/authRole/{userId}")
    @ApiOperation(value = "根据用户编号获取授权角色")
    @PreAuthorize("hasAuthority('system:user:query')")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = sysUserService.selectUserById(userId);
        List<SysRole> roles = sysRoleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    @PutMapping("/authRole")
    @ApiOperation(value = "用户授权角色")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        sysUserService.insertUserAuth(userId, roleIds);
        return AjaxResult.success();
    }

    @GetMapping(value = {"/", "/{userId}"})
    @ApiOperation(value = "获取用户详情")
    @PreAuthorize("hasAuthority('system:user:query')")
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        sysUserService.checkUserDataScope(userId);
        AjaxResult result = AjaxResult.success();
        List<SysRole> roles = sysRoleService.selectRoleAll();
        result.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        result.put("posts", sysPostService.selectPostAll());
        if (EmptyUtil.isNotEmpty(userId)) {
            result.put(AjaxResult.DATA_TAG, sysUserService.selectUserById(userId));
            result.put("postIds", sysPostService.selectPostListByUserId(userId));
            result.put("roleIds", sysRoleService.selectRoleListByUserId(userId));
        }
        return result;
    }

    @GetMapping("/list")
    @ApiOperation(value = "获取用户列表")
    @PreAuthorize("hasAuthority('system:user:list')")
    public CommonPage list(SysUser user,
                           @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                           @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> list = sysUserService.selectUserList(user);
        return CommonPage.restPage(list);
    }

    @GetMapping("/listDeleteUser")
    @ApiOperation(value = "获取已删除用户列表")
    @PreAuthorize("hasAuthority('system:user:recovery')")
    public CommonPage listDeleteUser(SysUser user,
                                     @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                     @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> list = sysUserService.selectDeleteUserList(user);
        return CommonPage.restPage(list);
    }

    @PutMapping("/recovery")
    @ApiOperation(value = "恢复已删除用户")
    @PreAuthorize("hasAuthority('system:user:recovery')")
    public AjaxResult recoveryDeleteUser(@RequestBody List<Long> ids) {
        sysUserService.recoveryDeleteUser(ids);
        return AjaxResult.success();
    }

    @DeleteMapping("/realDeleteUser")
    @ApiOperation(value = "彻底删除用户")
    @PreAuthorize("hasAuthority('system:user:recovery')")
    public AjaxResult realDeleteUser(@RequestBody List<Long> ids) {
        sysUserService.realDeleteUser(ids);
        return AjaxResult.success();
    }

    @GetMapping("/importTemplate")
    @ApiOperation(value = "导出模板")
    @PreAuthorize("hasAuthority('system:user:import')")
    public AjaxResult importTemplate() throws Exception {
        return AjaxResult.success(ExcelUtil.exportExcel(new ArrayList<>(), "员工信息表", "员工信息", SysUser.class, "员工信息"));
    }


    @GetMapping("/export")
    @ApiOperation(value = "导出用户列表")
    @PreAuthorize("hasAuthority('system:user:export')")
    public AjaxResult export(SysUser user) {
        List<SysUser> list = sysUserService.selectUserList(user);
        try {
            return AjaxResult.success(ExcelUtil.exportExcel(list, "员工信息表", "员工信息", SysUser.class, "员工信息"));
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }


    @PostMapping("/importData")
    @ApiOperation(value = "导入用户列表")
    @PreAuthorize("hasAuthority('system:user:import')")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        List<SysUser> list = ExcelUtil.importExcel(file, SysUser.class);
        sysUserService.importData(list, updateSupport);
        return AjaxResult.success();
    }

    @GetMapping("/profile")
    @ApiOperation(value = "获取个人信息")
    public AjaxResult profile() {
        SysUser user = sysUserService.getCurrentUser();
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", sysUserService.selectUserRoleGroup(user.getUserName()));
        ajax.put("postGroup", sysUserService.selectUserPostGroup(user.getUserName()));
        return ajax;
    }

    @PutMapping("/profile")
    @ApiOperation(value = "修改个人信息")
    public AjaxResult updateProfile(@RequestBody SysUser user) {
        sysUserService.updateProfile(user);
        return AjaxResult.success();
    }

    @PutMapping("/profile/updatePwd")
    @ApiOperation(value = "个人信息->重置密码")
    public AjaxResult updatePwd(String oldPassword, String newPassword) {
        sysUserService.updatePwd(oldPassword, newPassword);
        return AjaxResult.success();
    }

    @PostMapping("/profile/avatar")
    public AjaxResult updateAvatar(@RequestParam("avatar") MultipartFile file) {
        sysUserService.updateAvatar(file);
        return AjaxResult.success();
    }
}
